/******************************************************************************

	COPYRIGHT(C) JONAS 'SORTIE' TERMANSEN 2008, 2009, 2010.

	This file is part of Maxsi Engine.

	Maxsi Engine is free software: you can redistribute it and/or modify it
	under the terms of the GNU Lesser General Public License as published by
	the Free Software Foundation, either version 3 of the License, or (at your
	option) any later version.

	Maxsi engine is distributed in the hope that it will be useful, but WITHOUT
	ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
	FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
	for more details.

	You should have received a copy of the GNU Lesser General Public License
	along with Maxsi Engine. If not, see <http://www.gnu.org/licenses/>.

	MaxsiEngine.dll
	A general purpose C++ library for the Maxsi Technology Project.

	MaxsiCommand.cpp
	A function that converts a full command into smaller arguments

******************************************************************************/

#include "MaxsiEngine.h" 

#if 0

#include <direct.h>
#include <tlhelp32.h>
#include <stdio.h>
#include <Tlhelp32.h>

BeginMaxsiNamespace

bool CommandLineToArg(MESTR* Command, int* argc, char*** argv)
{
	if ( Command == NULL || argc == NULL || argv == NULL ) { return false; }

	bool	Quote			=	false;
	bool	Content			=	false;
	size_t	CommandLen		=	MESTRLEN(Command);
	int		NumCommands		=	1;
	size_t	I				=	0;

	for (I=0; I < CommandLen; I++)
	{
		if ( Command[I] == '"' )
		{
			Quote			=	!Quote;
			Content			=	true;
		}
		else if ( Command[I] == ' ' )
		{
			if (!Quote&&Content)
			{
				Content		=	false;

				NumCommands++;
			}
		}
		else
		{
			Content			=	true;
		}
	}

	*argv = new MESTR*[NumCommands];
	*argc = NumCommands;

	if ( *argv ) { return false; }
	
	size_t StrBegin		=	0;
	size_t StrLen		=	0;
	size_t CommandNum	=	0;
	
	for (I=0; I < CommandLen; I++)
	{
		if (Command[I] == '"')
		{
			Quote = !Quote;
			Content			=	true;
		}
		else if (Command[I] == ' ')
		{
			if ( !Quote && Content)
			{
				Content		=	false;

				StrLen = I - StrBegin;
				if (Command[StrBegin] == '"')
				{
					StrBegin++;
					StrLen--;
				}
				if (Command[StrBegin+StrLen-1] == '"')
				{
					StrLen-=1;
				}
				MESTR* Argument = 0;
				Argument = new MESTR[StrLen+1];

				if ( Argument )
				{				
					memcpy(Argument,Command + StrBegin,sizeof(MESTR)*StrLen);
					memset(Argument+StrLen,0,sizeof(MESTR));
				}

				(*argv)[CommandNum] = Argument;		

				CommandNum++;
				StrBegin = I+1;
			}
			else if ( !Quote )
			{
				StrBegin++;
			}
		}
		else
		{
			Content			=	true;
		}
	}
	StrLen = I - StrBegin;
	if (Command[StrBegin] == '"')
	{
		StrBegin++;
		StrLen--;
	}
	if (Command[StrBegin+StrLen-1] == '"')
	{
		StrLen-=1;
	}
	MESTR* Argument = new MESTR[StrLen+1];
	
	if ( Argument )
	{
		memcpy(Argument,Command + StrBegin,sizeof(MESTR)*StrLen);
		memset(Argument+sizeof(MESTR)*StrLen,0,1);
	}

	(*argv)[CommandNum] = Argument;

	return true;
}

void DeleteCommandLineArg(int argc, MESTR** argv)
{
	for ( int I = 0; I < argc; I++ )
	{
		delete[] argv[I];
	}
	delete[] argv;
}

bool RunProcess(MESTR* Command, HWND ForegroundWindow)
{
	LPSTARTUPINFOA si = new _STARTUPINFOM;
    LPPROCESS_INFORMATION pi = new _PROCESS_INFORMATION;

    ZeroMemory( si, sizeof(_STARTUPINFOA) );
    si->cb = sizeof(si);
    ZeroMemory( pi, sizeof(_PROCESS_INFORMATION) );

    // Start the child process. 
    if( !CreateProcessM( NULL,   // No module name (use command line)
        Command,        // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        0,              // No creation flags
        NULL,           // Use parent's environment block
        NULL,           // Use parent's starting directory 
        si,            // Pointer to STARTUPINFO structure
        pi )           // Pointer to PROCESS_INFORMATION structure
    ) 
    {
        return false;
    }

	if ((UINT_PTR)ForegroundWindow != SIZE_MAX )
	{

		if ( ForegroundWindow )
		{
			Sleep(100);
			SetForegroundWindow(ForegroundWindow);
		}

		// Wait until child process exits.
		WaitForSingleObject( pi->hProcess, INFINITE );
	}

    // Close process and thread handles. 
    CloseHandle( pi->hProcess );
    CloseHandle( pi->hThread );

	delete pi;
	delete si;
	return true;
}

char*	GetWorkingDirectory()
{
	char*	CurrentDirectory		=	0;
	char*	CurrentDirectory_TMP	=	_getcwd(NULL,0);

	size_t CurrentDirectory_TMP_Len = strlen(CurrentDirectory_TMP);

	if (CurrentDirectory_TMP[CurrentDirectory_TMP_Len-1] == '\\' ||
		CurrentDirectory_TMP[CurrentDirectory_TMP_Len-1] == '/')
	{
		CurrentDirectory = new char[CurrentDirectory_TMP_Len+1];
		strcpy_s(CurrentDirectory,CurrentDirectory_TMP_Len+1,CurrentDirectory_TMP);
	}
	else
	{
		CurrentDirectory = new char[CurrentDirectory_TMP_Len+2];
		strcpy_s(CurrentDirectory,CurrentDirectory_TMP_Len+1,CurrentDirectory_TMP);
		memset(CurrentDirectory+CurrentDirectory_TMP_Len,'\\',1);
		memset(CurrentDirectory+CurrentDirectory_TMP_Len+1,0,1);
	}

	free(CurrentDirectory_TMP);

	return CurrentDirectory;
}

bool	WaitForProcessToClose	(DWORD ProcessID)
{
	bool	ShouldRetry		=	true;

	while ( ShouldRetry )
	{
		ShouldRetry			=	false;

		HANDLE hProcessSnap;
		PROCESSENTRY32 pe32;

		// Take a snapshot of all processes in the system.
		hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );

		if( hProcessSnap == INVALID_HANDLE_VALUE )
		{
			return false;
		}

		// Set the size of the structure before using it.
		pe32.dwSize = sizeof( PROCESSENTRY32 );

		// Retrieve information about the first process,
		// and exit if unsuccessful
		if( !Process32First( hProcessSnap, &pe32 ) )
		{
			CloseHandle( hProcessSnap );          // clean the snapshot object
			return true;
		}

		// Now walk the snapshot of processes, and
		// display information about each process in turn
		do
		{
			if ( pe32.th32ProcessID == ProcessID ) 
			{
				ShouldRetry	=	true;
			}


		} while( Process32Next( hProcessSnap, &pe32 ) );

		CloseHandle( hProcessSnap );

		if ( ShouldRetry )
		{
			// Wait a little while.
			Sleep(50);
		}
	}

	return true;
}

EndMaxsiNamespace

#endif
